package com.shijf.ds;

public class LinkedList {
    Node head; //头结点
    public LinkedList(){
        this.head = null;
    }

    //向链表中添加元素，尾部添加
    public void add(int element){
        Node newNode = new Node(element);
        if(head == null){
            head = newNode;
            return;
        }

        //临时节点记录头部节点，找到最后一个节点，尾插法
        Node temp = head;
        while(temp.next != null){
            temp = temp.next;
        }
        temp.next = newNode;
    }

    //从链表中删除元素
    public void del(int element){
        //链表为空返回
        if(head == null){
            return;
        }
        //第一个值刚好是要查找的值，则第二个节点成为头部节点
        if(head.val == element){
            head = head.next;
            return;
        }

        //遍历链表查找元素
        Node temp = head;
        while(temp.next != null && temp.next.val != element){
            temp = temp.next;
        }
        if(temp.next != null && temp.next.val == element){
            temp.next = temp.next.next;
        }
    }

    //打印链表中元素
    public void printList(){
        Node temp = head;
        while (temp != null){
            System.out.println(temp.val);
            temp = temp.next;
        }
    }


    public static void main(String[] args) {
        LinkedList ll = new LinkedList();
        ll.printList();
        ll.add(1);
        ll.add(2);
        ll.add(3);
        ll.del(2);
        ll.printList();
    }
}

class Node{
    int val;
    Node next;
    public Node(int val){
        this.val = val;
    }
}
